package xhwl.insurance.ui.fragment;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.media.Image;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.trello.rxlifecycle.components.support.RxFragmentActivity;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import xhwl.android.common.log.XHLog;
import xhwl.android.common.util.SPUtil;
import xhwl.android.common.util.StringUtil;
import xhwl.android.common.util.ToastUtil;
import xhwl.insurance.R;
import xhwl.insurance.adapter.ForumListNewAdapter;
import xhwl.insurance.dialog.VideoShareDialog;
import xhwl.insurance.event.FreshForumListEvent;
import xhwl.insurance.http.api.ForumListApi;
import xhwl.insurance.http.api.ForumThumbsUpApi;
import xhwl.insurance.http.api.UnReadMsgCountApi;
import xhwl.insurance.http.bean.resp.ForumProductResp;
import xhwl.insurance.http.bean.resp.UnReadMsgResp;
import xhwl.insurance.http.bean.resp2.HttpResp;
import xhwl.insurance.ui.ForumSearchActivity;
import xhwl.insurance.ui.MessageCenterActivity;
import xhwl.insurance.ui.PutQuestionsActivity;
import xhwl.insurance.ui.PutQuestionsStyleActivity;
import xhwl.insurance.ui.voicesupport.MediaPlay;
import xhwl.pulltorefresh.PullToRefreshRecyclerView;
import xhwl.pulltorefresh.callback.PullToRefreshListener;
import xhwl.retrofitrx.BaseApi;
import xhwl.retrofitrx.HttpException;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

/**
 * Created by fuyi on 2017/9/26.
 * 论坛页面
 */

public class ForumFragment extends BaseFragment implements View.OnClickListener, PullToRefreshListener {

    private List<ForumProductResp> ForumList = new ArrayList<>();
    private ForumListNewAdapter mForumAdapter;
    private PullToRefreshRecyclerView recyclerView;
    String mPage = "1";
    private VideoShareDialog shareDialog;
    private TextView mTv_search;
    private RelativeLayout rl_bell_info;
    private String searchText;
    private ImageView iv_bell_info;
    TextView tvUnRead;
    private View mView;
    private AnimationDrawable ad;
    private View animeView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_forum, null);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    protected void initView(View view) {
        initTitleViews(view);
        recyclerView = (PullToRefreshRecyclerView) view.findViewById(R.id.recyclerView);
        rl_bell_info = (RelativeLayout) view.findViewById(R.id.rl_bell_info);
        iv_bell_info = (ImageView) view.findViewById(R.id.iv_bell_info2);
        tvUnRead = (TextView) view.findViewById(R.id.tvUnRead2);
        tvUnRead.setVisibility(View.GONE);
        rl_bell_info.setVisibility(View.VISIBLE);
        mView = (View)view.findViewById(R.id.v_anime);
        initRecylerView();
        mForumAdapter = new ForumListNewAdapter(mActivity, ForumList);
        recyclerView.setAdapter(mForumAdapter);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 2) {
            searchText = data.getExtras().getString("SearchText");
            mTv_search.setText(searchText);
            getForumData("1", searchText);
        } else if (resultCode == 3) {
            searchText = data.getExtras().getString("SearchText");
            mTv_search.setText(searchText);
            getForumData("1", searchText);
        }else if (resultCode==4){
            searchText = data.getExtras().getString("SearchText");
            mTv_search.setText(searchText);
            getForumData("1", "");
        }
    }

    private void initRecylerView() {
        //添加HeaderView
        View headView = View.inflate(mActivity, R.layout.layout_find_head, null);
        RelativeLayout mSearch = (RelativeLayout) headView.findViewById(R.id.rl_search_find);
        mTv_search = (TextView) headView.findViewById(R.id.tv_search_finds);
        mSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(mActivity, ForumSearchActivity.class);
                startActivityForResult(intent, 1);
            }
        });
        recyclerView.addHeaderView(headView);
        //设置EmptyView
        View emptyView = View.inflate(mActivity, R.layout.layout_empty_view, null);
        emptyView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        recyclerView.setEmptyView(emptyView);

        final LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);


            }
        });
        //设置是否开启上拉加载
        recyclerView.setLoadingMoreEnabled(true);
        //设置是否开启下拉刷新
        recyclerView.setPullRefreshEnabled(true);
        //设置是否显示上次刷新的时间
        recyclerView.displayLastRefreshTime(false);
    }

    @Override
    protected void setUpTitleView() {
        titleTextView.setText("论坛");
        llBack.setVisibility(View.GONE);
        leftTextView.setVisibility(View.VISIBLE);
        leftTextView.setText("提问");
    }

    @Override
    protected void initListener() {
        iv_bell_info.setOnClickListener(this);

        leftTextView.setOnClickListener(this);
        //设置刷新回调
        recyclerView.setPullToRefreshListener(this);
        mForumAdapter.setOnItemClickLitener(new ForumListNewAdapter.OnItemClickLitener() {
            private UMImage image;
            private String[] picUrl;

            @Override
            public void onItemClick(int position) {

            }

            @Override
            public void onShareClick(final int position) {
                shareDialog = new VideoShareDialog(mActivity);
                shareDialog.setCancelable(false);
                shareDialog.setCanceledOnTouchOutside(false);
                View dialog = View.inflate(mActivity, R.layout.dialog_videoshare, null);
                RelativeLayout mWxCircle = (RelativeLayout) dialog.findViewById(R.id.rl_wxcircle);
                RelativeLayout mWechat = (RelativeLayout) dialog.findViewById(R.id.rl_wechat);
                RelativeLayout mCopy = (RelativeLayout) dialog.findViewById(R.id.rl_copy);
                TextView mCancel = (TextView) dialog.findViewById(R.id.btn_videocancel);
                shareDialog.setContentView(dialog);
                shareDialog.show();
                if ("2" != ForumList.get(position - 1).getPOST_TYPE() && ForumList.get(position - 1).getVI_PI_URL() != null) {
                    String url = ForumList.get(position - 1).getVI_PI_URL();
                    picUrl = url.split(";");
                    if (picUrl[0]==null) {
                        image = new UMImage(mActivity, R.drawable.hmo_logo);
                    }else{
                        image = new UMImage(mActivity, picUrl[0]);
                    }
                }
//                final UMImage image = new UMImage(mActivity, picUrl[0]);
                mWxCircle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        new ShareAction(mActivity)
                                .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                                .setCallback(shareListener)
                                .withTitle(ForumList.get(position - 1).getPOST_TITLE())
                                .withTargetUrl("http://wx-heartorg.yk2020.com/weixin/index.php?m=Member&c=Index&a=share"+"&post_id="+ForumList.get(position-1).getPOST_ID())
                                .withText("http://wx-heartorg.yk2020.com/weixin/index.php?m=Member&c=Index&a=share"+"&post_id="+ForumList.get(position-1).getPOST_ID())
                                .withMedia(image)
                                .share();

                    }
                });

                mWechat.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        new ShareAction(mActivity)
                                .setPlatform(SHARE_MEDIA.WEIXIN)
                                .setCallback(shareListener)
                                .withTitle(ForumList.get(position - 1).getPOST_TITLE())
                                .withTargetUrl("http://wx-heartorg.yk2020.com/weixin/index.php?m=Member&c=Index&a=share"+"&post_id="+ForumList.get(position-1).getPOST_ID())
                                .withText("http://wx-heartorg.yk2020.com/weixin/index.php?m=Member&c=Index&a=share"+"&post_id="+ForumList.get(position-1).getPOST_ID())
                                .withMedia(image)
                                .share();
                    }
                });
                mCopy.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(!StringUtil.isEmpty(ForumList.get(position-1).getPOST_ID())){
                            ClipboardManager cmb = (ClipboardManager)mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
                            cmb.setText("http://wx-heartorg.yk2020.com/weixin/index.php?m=Member&c=Index&a=share"+"&post_id="+ForumList.get(position-1).getPOST_ID());
                            ToastUtil.showToast(mActivity,"链接已复制");
                        }else {
                            ToastUtil.showToast(mActivity,"该帖子没有链接");
                        }

                    }
                });

                mCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        shareDialog.dismiss();
                    }
                });

            }


            @Override
            public void onGoodClick(final int position, final ImageView imageview, final TextView textview) {
                String member_id = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID, "");
                ForumThumbsUpApi api = new ForumThumbsUpApi(ForumList.get(position - 1).getPOST_ID(), member_id);
                HttpManager.getInstance().dealHttp(ForumFragment.this, api, new OnNextListener<HttpResp>() {
                            @Override
                            public void onNext(HttpResp httpResp) {
                                if (httpResp.isOk()) {
                                    ForumList.get(position - 1).isSelected = !ForumList.get(position - 1).isSelected;
                                    int thumbs = Integer.valueOf(ForumList.get(position - 1).getTHUMBS_UP()).intValue();
                                    int thubs2 = thumbs += 1;
                                    int thubs3 = thumbs -= 1;
                                    XHLog.e("thumbs:" + thumbs);
                                    if (ForumList.get(position - 1).getTHUMBS_FLAG().equals("1")) {
                                        int thubs4 = thumbs -= 1;
                                        int thubs5 = thumbs += 1;
                                        XHLog.e("thubs4:" + thubs4);
                                        XHLog.e("thubs5:" + thubs5);
                                        imageview.setImageResource(ForumList.get(position - 1).isSelected ? R.drawable.icon_thumbs_up : R.drawable.icon_thumbs_up2);
                                        textview.setText(ForumList.get(position - 1).isSelected ? thubs4 + "" : thubs5 + "");
                                    } else {
                                        XHLog.e("thubs3:" + thubs3);

                                        XHLog.e("thubs2:" + thubs2);
                                        imageview.setImageResource(ForumList.get(position - 1).isSelected ? R.drawable.icon_thumbs_up2 : R.drawable.icon_thumbs_up);
                                        textview.setText(ForumList.get(position - 1).isSelected ? thubs2 + "" : thubs3 + "");
                                    }
                                } else {
                                    ToastUtil.showToast(mActivity, httpResp.message);
                                }

                            }

                            @Override
                            public void onError(HttpException ex) {
                                super.onError(ex);
                            }
                        }
                );

            }

            @Override
            public void onVoicePlay(int position, final View mView) {
//                Toast.makeText(getContext(), "mView"+mView, Toast.LENGTH_SHORT).show();
                if (animeView!=null){
                    animeView.setBackgroundResource(R.drawable.adj_voice);
                    animeView = null;
                }
                animeView = mView.findViewById(R.id.v_anime);
                animeView.setBackgroundResource(R.drawable.voice_forum_animation);
                ad = (AnimationDrawable) animeView.getBackground();
                ad.start();
               //播放录制的音频
                MediaPlay.playAudio(ForumList.get(position-1).getVI_PI_URL(), new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        //播放完成，停止动画效果
                        animeView.setBackgroundResource(R.drawable.adj_voice);

                    }
                });
            }
        });


    }

    @Override
    public void onResume() {
        //加载论坛数据
        getForumData("1", searchText);
        getUnReadMsgCount();
        super.onResume();
        if (ad!=null) {
            ad.stop();
            animeView.setBackgroundResource(R.drawable.adj_voice);
        }
    }

    @Override
    protected void loadData() {
        //加载论坛数据
        getForumData("1", "");

    }

    private void getForumData(final String page, String SearchText) {
        String member_id = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID, "");
        BaseApi api = new ForumListApi(member_id, SearchText, page);
        HttpManager.getInstance().dealHttp((RxFragmentActivity) getActivity(), api, new OnNextListener<HttpResp<ArrayList<ForumProductResp>>>() {

            @Override
            public void onNext(HttpResp<ArrayList<ForumProductResp>> forumProductResps) {
                if (page == "1") {
                    if (forumProductResps != null) {
                        recyclerView.setRefreshComplete();
                        if (forumProductResps.isOk()) {
                            mPage = "1";
                            ForumList.clear();
                            if (forumProductResps.data != null && forumProductResps.data.size() > 0) {
                                ForumList.addAll(forumProductResps.data);
                            }
                            mForumAdapter.notifyDataSetChanged();
                        } else {
                            ToastUtil.showToast(mActivity, forumProductResps.message);
                        }
                    } else {
                        recyclerView.setRefreshFail();
                    }
                } else {
                    if (forumProductResps != null) {
                        recyclerView.setLoadMoreComplete();
                        if (forumProductResps.isOk()) {
                            if (forumProductResps.data != null && forumProductResps.data.size() > 0) {
                                mPage = page;
                                ForumList.addAll(forumProductResps.data);
                                mForumAdapter.notifyDataSetChanged();
                            } else {
                                ToastUtil.showToast(mActivity, getString(R.string.no_more_data));
                            }
                        } else {
                            ToastUtil.showToast(mActivity, forumProductResps.message);
                        }
                    } else {
                        recyclerView.setLoadMoreFail();
                    }
                }
            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
                if (page == "1") {
                    recyclerView.setRefreshFail();
                } else {
                    recyclerView.setLoadMoreFail();
                }
            }
        });

    }

    private void getUnReadMsgCount() {
        String memberId = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID, "");
        if (StringUtil.isEmpty(memberId)) {
            return;
        }
        UnReadMsgCountApi api = new UnReadMsgCountApi(memberId);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<UnReadMsgResp>() {
            @Override
            public void onNext(UnReadMsgResp resp) {
                if (resp != null && !StringUtil.isEmpty(resp.NUM)) {
                    if (!"0".equals(resp.NUM)) {
                        tvUnRead.setVisibility(View.VISIBLE);
                        tvUnRead.setText(resp.NUM);
                    } else {
                        tvUnRead.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.title_left_textview:
//                Intent intent = new Intent();
//                intent.setClass(getActivity(), PutQuestionsActivity.class);
//                startActivity(intent);
//                break;
            case R.id.iv_bell_info2://消息
                getActivity().startActivity(new Intent(getActivity(), MessageCenterActivity.class)
                        .putExtra("BACK_STATE","0"));
                break;
            case R.id.title_left_textview://后续开发先跳转到提问方式选择界面
                Intent intent = new Intent();
                intent.setClass(getActivity(), PutQuestionsStyleActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }

    }


    @Override
    public void onRefresh() {
        //加载论坛数据
        getForumData("1", "");
        mTv_search.setText("大家都在搜百倍爱心卡");

    }

    @Override
    public void onLoadMore() {
        getForumData(mPage + 1, "");

    }

    private UMShareListener shareListener = new UMShareListener() {

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            ToastUtil.showToast(mActivity, "分享成功！");
            if (shareDialog != null && shareDialog.isShowing()) {
                shareDialog.dismiss();
            }
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            ToastUtil.showToast(mActivity, "分享失败！");
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            ToastUtil.showToast(mActivity, "取消分享");

        }
    };

    public void onEvent(FreshForumListEvent event) {
        getForumData("1", "");
        mTv_search.setText("大家都在搜百倍爱心卡");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (ad!=null) {
            ad.stop();
            animeView.setBackgroundResource(R.drawable.adj_voice);
        }
        MediaPlay.onRelease();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (ad!=null) {
            ad.stop();
            animeView.setBackgroundResource(R.drawable.adj_voice);
        }
        MediaPlay.onRelease();
    }
}
